<template>
  <!-- 搜索区域 -->
  <el-row class="search-area" :gutter="15" style="margin-bottom: 20px" align="middle">
    <el-col :span="2.5" style="margin-left: 10px">
      <span class="label">供应商名称:</span>
    </el-col>
    <el-col :span="4">
      <el-input placeholder="请输入" v-model="search.name" />
    </el-col>

    <el-col :span="2.5">
      <span>销售联系人:</span>
    </el-col>
    <el-col :span="4">
      <el-input placeholder="请输入" v-model="search.contactName" />
    </el-col>

    <el-col :span="2.5">
      <span>销售联系电话:</span>
    </el-col>
    <el-col :span="4">
      <el-input placeholder="请输入" v-model="search.saleNumber" />
    </el-col>

    <el-col :span="4" style="text-align: right">
      <el-button color="#2F4050" @click="handleSearch">查询</el-button>
      <el-button color="#2F4050" @click="handleReset" style="margin-left: 10px">重置</el-button>
    </el-col>
  </el-row>

  <!-- 操作区域: 按钮靠右 -->
  <el-row :gutter="15" style="margin-bottom: 20px">
    <el-col :span="23" style="text-align: right">
      <el-button color="#2F4050" @click="handleAdd">添加</el-button>
      <el-button color="#2F4050" style="margin-left: 10px" @click="handleExport">导出</el-button>
    </el-col>
  </el-row>

  <!-- 表格数据 -->
  <el-table :data="tableData" style="width: 100%">
    <el-table-column fixed prop="name" label="供应商公司名称" width="125" align="center" />
    <el-table-column prop="contact_name" label="销售联系人" width="95" align="center" />
    <el-table-column prop="sale_number" label="销售联系电话" width="108" align="center" />
    <el-table-column prop="fication" label="主营产品类型" width="108" align="center" />
    <el-table-column prop="quotation" label="报价系数" width="80" align="center" />
    <el-table-column prop="delivery" label="交付率" width="70" align="center" />
    <el-table-column prop="quality" label="质量投诉率" width="95" align="center" />
    <el-table-column prop="delay" label="延误交付率" width="100" align="center" />
    <el-table-column prop="annual" label="年度采购余额" width="110" align="center" />
    <el-table-column label="账号状态(启用/禁用)" width="90" align="center">
      <template #default="{ row }">
        <el-switch v-model="row.status" @click="handleStatusChange(row)" :active-value="1" :inactive-value="0"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
      </template>
    </el-table-column>
    <!-- 表格操作列 -->
    <el-table-column fixed="right" label="操作" min-width="120" align="center">
      <template #default="{ row }">
        <!-- 注意这里的 row 参数 -->
        <el-button link type="primary" size="small" @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button :loading="isLoading" link type="primary" size="small"
          @click="handleResetPassword(row)">重置密码</el-button>
        <el-button link type="primary" size="small" @click="() => handleDelete(row)">
          删除
        </el-button>
        <el-button link type="primary" size="small">累计采购</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 编辑表单 -->
  <el-dialog v-model="editDialogVisible" title="编辑供应商信息">
    <el-form :model="editForm" label-width="120px">
      <el-form-item label="供应商名称">
        <el-input v-model="editForm.name" :disabled="!editForm.name"></el-input>
      </el-form-item>
      <el-form-item label="销售联系人">
        <el-input v-model="editForm.contact_name" :disabled="!editForm.contact_name"></el-input>
      </el-form-item>
      <el-form-item label="销售联系电话">
        <el-input v-model="editForm.sale_number" :disabled="!editForm.sale_number"></el-input>
      </el-form-item>
      <el-form-item label="主营产品类型">
        <el-input v-model="editForm.fication" :disabled="!editForm.fication"></el-input>
      </el-form-item>
      <el-form-item label="报价系数">
        <el-input v-model="editForm.quotation" :disabled="!editForm.quotation"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit(editForm)">保存</el-button>
    </span>
  </el-dialog>

  <!--分页-->
  <div style="background-color: #fff; height: 50px; line-height: 50px; text-align: right">
    <el-pagination background :page-size="pageSize" layout="total,sizes,prev, pager, next,jumper" :total="total"
      @size-change="chgsize" @current-change="chgpg" />
  </div>
</template>

<script lang="ts" setup>
import { querySupplier } from "@/api/supplier/supplier";
import {
  querySupplierByInfo,
  changeStatus,
  deleteInfomation,
  editSupplier,
  resetPasswordInfo,
} from "@/api/supplier/supplier";
import { ref, onMounted, Ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 引入路由
import { useRouter } from "vue-router";
// 引入xlsx，用于文件导出
import * as XLSX from 'xlsx';
// 路由实例
const router = useRouter();

//分页信息
const page = ref(1); //当前页 默认第1页
const pageSize = ref(10); //每页记录数
const total = ref(0); //总记录数

// 表格行的数据类型定义
interface TableRow {
  id: number;
  name: string;
  contact_name: string;
  sale_number: string;
  fication: string;
  quotation: string;
  delivery: number;
  quality: number;
  delay: number;
  annual: number;
  status: number; // 例如：1为启用，0为禁用
}
// 编辑表单数据
const editForm = ref({
  id: 0,
  name: "",
  contact_name: "",
  sale_number: "",
  fication: "",
  quotation: "",
});
// 编辑对话框是否显示
const editDialogVisible = ref(false);
// 编辑按钮点击事件
const handleEdit = (row) => {
  editForm.value = { ...row };
  editDialogVisible.value = true;
};
// 提交编辑
const submitEdit = async (formData) => {
  console.log("提交编辑:>>>", JSON.parse(JSON.stringify(formData)));
  try {
    const res = await editSupplier(formData);
    if (res?.code == 200) {
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      editDialogVisible.value = false;
      initData();
    } else {
      ElMessage({
        message: res?.msg || "编辑失败，请重试！",
        type: "warning",
      });
    }
  } catch (error) {
    ElMessage({
      message: "请求失败，请检查网络连接或参数设置。",
      type: "error",
    });
  }
};
// 初始化 tableData
const tableData = ref<TableRow[]>([]);

//过滤条件
const filters = ref({
  company: "",
  contactName: "",
});

//每页记录数变化
function chgsize(size) {
  //更改每页记录数
  pageSize.value = size;
  //从每页开始查询
  page.value = 1;
  //查询数据
  initData();
}
//页面发生变化
function chgpg(pg) {
  //更改当前页
  page.value = pg;
  //查询数据
  initData();
}
//查询数据
async function initData() {
  //请求
  let data = {
    page: page.value,
    pageSize: pageSize.value,
    company: filters.value.company,
    contactName: filters.value.contactName,
  };
  let res = await querySupplier(data);
  // console.log("完整返回信息>>>", res);
  if (res.code == 200) {
    tableData.value = res.data;
    // console.log("信息>>>" + JSON.stringify(tableData.value, null, 2));
    //接收分页信息
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
    total.value = res.data.total;
  }
}
//生命周期钩子
onMounted(() => {
  initData();
});

// 搜索条件
const search = ref({
  name: "",
  saleNumber: "",
  contactName: "",
});

// 重置
const handleReset = () => {
  search.value.contactName = "";
  search.value.name = "";
  search.value.saleNumber = "";
  // tableData.value = [...tableData];
};

// 条件查询
const handleSearch = async () => {
  //请求
  let data = {
    // 映射前端 search.value 到后端需要的参数
    name: search.value.name,
    saleNumber: search.value.saleNumber,
    contactName: search.value.contactName,
  };
  let res = await querySupplierByInfo(data); // 将 data 作为参数传递
  console.log("查询条件》》", data);
  console.log("条件查询完整返回信息>>>", res);
  if (res?.code == 200) {
    tableData.value = res.data;
    //接收分页信息
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
    total.value = res.data.total;
  }
};

// 状态修改
const handleStatusChange = async (row) => {
  // 更改前确认
  const confirmResult = await ElMessageBox.confirm(
    `您确定要${row.status === 1 ? "启用" : "禁用"}该供应商账号吗?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).catch(() => {
    // 如果用户取消操作，则恢复原来的值
    row.status = row.status === 1 ? 0 : 1;
    return false;
  });

  if (!confirmResult) return; // 如果不是确定操作，则直接返回

  // 请求数据准备
  let data = {
    id: row.id,
    account: row.account,
    status: row.status, // 新的状态值
  };

  // 发送请求给后端
  let res = await changeStatus(data);

  if (res?.code == 200) {
    ElMessage({
      type: "success",
      message: `账号状态${row.status === 1 ? "启用" : "禁用"}成功`,
    });
  } else {
    // 如果状态更新失败，回滚状态
    row.status = row.status === 1 ? 0 : 1;
    ElMessage({
      message: res.msg || "状态修改失败，请重试！",
      type: "warning",
    });
  }
};

// 信息删除
const deleteInfo = async (id) => {
  try {
    console.log("Deleting with ID:", id); // 添加日志
    let res = await deleteInfomation(id);
    if (res?.code == 200) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      initData();
    } else {
      ElMessage({
        message: res.msg || "删除失败，请重试！",
        type: "warning",
      });
    }
  } catch (error) {
    console.error("Error during delete:", error); // 错误日志
    ElMessage({
      message: "请求失败，请检查网络连接或参数设置。",
      type: "error",
    });
  }
};

// 删除
const handleDelete = async (row: TableRow) => {
  const confirmResult = await ElMessageBox.confirm(
    `您确定要删除供应商"${row.name}"吗？`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).catch(() => false);

  if (confirmResult) {
    await deleteInfo(row.id);
  }
};

// 密码重置
const isLoading = ref(false);

const handleResetPassword = async (row: TableRow) => {
  const confirmResult = await ElMessageBox.confirm(
    `您确定要重置供应商"${row.name}"的密码吗？`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).catch(() => false);

  if (confirmResult) {
    isLoading.value = true; // 开始加载
    try {
      await resetPasswordInfo(row.id);
      ElMessage({
        message: "密码重置成功",
        type: "success",
      });
    } catch (error) {
      console.error("重置密码操作失败:", error);
      ElMessage({
        message: "重置密码失败，请重试！",
        type: "error",
      });
    } finally {
      isLoading.value = false; // 完成加载
    }
  }
};
// 跳转到添加页面
const handleAdd = () => {
  router.push({
    path: "/supplier/add",
  });
};
// 导出功能实现
const handleExport = () => {
  // Step 1: 提取表格数据
  const rows = tableData.value.map(row => ({
    "供应商公司名称": row.name,
    "销售联系人": row.contact_name,
    "销售联系电话": row.sale_number,
    "主营产品类型": row.fication,
    "报价系数": row.quotation,
    "交付率": row.delivery,
    "质量投诉率": row.quality,
    "延误交付率": row.delay,
    "年度采购余额": row.annual,
    "账号状态(启用/禁用)": row.status === 1 ? '启用' : '禁用',
  }));
  // Step 2: 使用 SheetJS 创建工作簿
  const ws = XLSX.utils.json_to_sheet(rows);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "供应商数据");

  // Step 3: 导出为 Excel 文件
  XLSX.writeFile(wb, '供应商数据.xlsx');
};
</script>
<style scoped>
.search-area {
  margin-top: 10px;
}
</style>
